package com.javafactroy.kunlong.base.advice;


import com.javafactroy.kunlong.base.annotation.CheckDate;
import com.javafactroy.kunlong.base.annotation.CheckParams;
import com.javafactroy.kunlong.client.feign.dto.ApiResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = {
        "com.javafactroy.kunlong.web.generalquery",
        "com.javafactroy.kunlong.web.generalreport",
        "com.javafactroy.kunlong.web.generalright",
        "com.javafactroy.kunlong.web.metadata",
        "com.javafactroy.kunlong.web.dbagent",
        "com.javafactroy.kunlong.web.codefactroy"})
public class CommonRespBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnType.getDeclaringClass().isAnnotationPresent(CheckParams.class)) {
            //若在类中加了@ResponseNotIntercept 则该类中的方法不用做统一的拦截
            return false;
        }
        if (returnType.getMethod().isAnnotationPresent(CheckDate.class)) {
            //若方法上加了@ResponseNotIntercept 则该方法不用做统一的拦截
            return false;
        }
        return true;
    }


    @Override
    public ApiResult beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                     Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                     ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ApiResult) {
            // 提供一定的灵活度，如果body已经被包装了，就不进行包装
            return (ApiResult) body;
        }
        if (body instanceof String) {
            //解决返回值为字符串时，不能正常包装
            return ApiResult.success(body);

        }
        return ApiResult.success(body);
    }
}
